package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()  // 禁用CSRF保护
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 使用无状态会话
            .and()
            .authorizeRequests()
            .antMatchers(
                "/users/login",     // 登录接口
                "/users/register",  // 注册接口
                "/users/check-usercode",  // 检查用户码
                "/users/check-email",     // 检查邮箱
                "/organizations",    // 添加组织接口，允许未认证访问
                "/organizations/**"  // 添加所有组织相关接口，允许未认证访问
            ).permitAll()
            .antMatchers("/questions/list").permitAll()  // 允许未认证访问题目列表
            .antMatchers("/questions/**").authenticated()  // 其他题目相关接口需要认证
            .antMatchers("/test-records/**").authenticated()  // 测试记录相关接口需要认证
            .antMatchers("/**").authenticated()  // 其他API接口需要认证
            .anyRequest().permitAll()  // 其他请求允许访问
            .and()
            .httpBasic().disable()  // 禁用基本认证
            .formLogin().disable()  // 禁用表单登录
            .headers().frameOptions().disable()  // 允许iframe
            .and()
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);  // 添加JWT过滤器
    }
} 